package com.hz.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hz.web.entity.MenuEntity;
import com.hz.web.entity.UserEntity;
import com.hz.web.service.ImenuService;
import com.hz.web.service.IuserService;
import com.hz.web.util.Constant;


@Controller
public class loginController {

	@Resource
	private  IuserService userService;
	
	@Resource
	private ImenuService menuService;//菜单管理
	
	@RequestMapping("login")
	public String tologin (){	
		return "login";
	}
	
	@RequestMapping("removeSession")
	@ResponseBody
	public Object removeSession(HttpSession session){
		
		if(session.getAttribute("userinfo")!=null){
			session.removeAttribute("userinfo");
		}
		return 200;
	}
	
	@RequestMapping("loginMenu")
	public String loginMenu(Model model,HttpSession session,String adminCode,String adminPass){
		Map<String, Object> map = new HashMap<String, Object>();
		UserEntity entity =null;
		
		if(session.getAttribute("userinfo")!=null){
			entity = (UserEntity) session.getAttribute("userinfo");
			if((adminCode!=null && !"".equals(adminCode.trim()) )|| 
					(adminPass!=null && !"".equals(adminPass.trim()))){
				map.put("name", adminCode);
				map.put("pass", adminPass);
				entity = userService.queryUser(map);
			}
		}else{
			if(adminCode==null || "".equals(adminCode.trim()) || adminPass==null || "".equals(adminPass.trim()) ){
				return "login";
			}
			
			map.put("name", adminCode.trim());
			map.put("pass", adminPass.trim());
			
			entity = userService.queryUser(map);
		}
		
		if(entity==null){
			model.addAttribute("msg", "用户名或密码错误！");
			return "login";
		}
		session.setAttribute("userinfo", entity);
		
		//登录成功后，查询菜单
		Map<String, Object> rolemap = new HashMap<String, Object>();
		rolemap.put("parentId", Constant.MENU_PARENT_FIRST);
		rolemap.put("roleId",entity.getRoleId());
		List<MenuEntity> ls = menuService.queryNodes(rolemap);//只获取第一级目录
		model.addAttribute("ls", ls);
		
		return "index";
	}
	
}
